﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VTLive.Models;

namespace VTLive.Controllers
{   
    public class SessionController : BaseController
    {
        //SessionController heldur utan um innskráningu og skráningu notenda


        //Login er Get fall sem skilar LogIn View-inu.
        public ActionResult LogIn()
        {
            return View();
        } 
        

        //Post fall sem tekur við upplýsingum úr LogIn View-inu, 
        //veitir heimild og sannreynir upplýsingarnar úr View-inu.
        //Fallið skilar Forsíðunni
        [HttpPost]
        public ActionResult LogIn(FormCollection collection)
        {
            UserRepository Users = new UserRepository(  );
            User User = Users.Authenticate(collection["UserName"], collection["Password"]);
            if (User == null)
            {
                TempData["Error"] = "Sorry but there is no such UserName/Password pair.";
                return RedirectToAction("LogIn");
            }
            else Session["user_id"] = User.ID;
            return RedirectToAction("Index", "Home");
        }

        //Fallið lokar á aðgengi notenda að ákveðnum hlutum kerfisins
        //Fallið skilar forsíðunni.
        public ActionResult LogOff()
        {
            Session.Abandon();
            return RedirectToAction("Index", "Home");
        }

        //Fallið birtir form til nýskráningar notanda
        public ActionResult Register()
        {
            RegisterViewModel User = new RegisterViewModel();
            return View("Register", User);
        }

        //Fallið tekur við nýskráningarformi, sannreynir upplýsingarnar
        //og skráir nýan notanda í gagnagrunn ef við á.
        [HttpPost]
        public ActionResult Register(FormCollection collection)
        {
            UserRepository db = new UserRepository();
            User User = new User();
            if (Request.Form["User.Password"] == Request.Form["ConfirmPassword"])
            {
                User.Username = Request.Form["User.Username"];
                User.Password = Request.Form["User.Password"];
                db.Add(User);
                db.Save();
                Session["user_id"] = db.GetUserByUserName(Request.Form["User.Username"]).ID;
                return RedirectToAction("Index", "Home");
            }
            else
            {
                RegisterViewModel RegModel = new RegisterViewModel();
                TempData["Error"] = "Password and ConfirmPassword do not match";
                return RedirectToAction("Register",RegModel);
            }

        }
    }
}
